<template>
  <div class="system-menu-container">
    <div class="breadcrumb-box">
      <Breadcrumb />
    </div>

    <div class="header-search flex space-between">
      <el-card shadow="hover" class="search-l">
        <span class="search-txt">查找病人</span>
        <el-input class="search-item" placeholder="请输入序号/姓名/手机号/住院号" v-model="state.apiData.search" size="default"
          style="width: 220px;" clearable @change="searchChange()">
        </el-input>

        <span class="search-txt">就诊科室</span>
        <el-select class="search-item" v-model="state.apiData.departmentId" placeholder="请选择科室" size="default"
          style="width: 150px;" clearable @change="searchChange">
          <el-option v-for="(item, index) in state.departmentList" :key="index" :label="item.departmentName"
            :value="item.id"></el-option>
        </el-select>

        <div class=" " style="margin-top:10px">
          <span class="search-txt">录入日期</span>
          <el-date-picker v-model="state.apiData.recordAt" type="daterange" range-separator="至" start-placeholder="录入开始日期"
            end-placeholder="录入结束日期" size="default" value-format="YYYY-MM-DD" @change="recordAtChange" clearable />
        </div>

        <!-- <div class="search-date-picker-box search-item">
          <el-date-picker v-model="state.apiData.operationAt" type="daterange" range-separator="至"
            start-placeholder="手术开始日期" end-placeholder="手术结束日期" size="default" value-format="YYYY-MM-DD"
            @change="operationAtChange" clearable />
        </div> -->
      </el-card>


      <el-card shadow="hover" class="search-r">

        <div class="time-line flex ">
          <div class="time-top flex space-between align-center">
            <el-button @click="nextOrPrevDayArr('prev')" :icon="ArrowLeftBold" size="default"
              style="padding: 0 0 0 4px;" />
            <div class="time-list" style="white-space: nowrap;">
              <div class="time-item" v-for="(item, index) in state.dayArr" :key="index"
                :class="item == state.checkedDay ? 'active' : ''" @click="changeDay(item)">
                {{ formatValue(item) }}
              </div>
            </div>
            <el-button @click="nextOrPrevDayArr('next')" :icon="ArrowRightBold" size="default"
              style="padding: 0 0 0 4px;" />
          </div>
        </div>
        <div>
          <el-radio-group v-model="state.hospitalAreaId" size="default" @change="searchBedChange">
            <el-radio-button v-for="(item, index) in state.hospitalAreaList" :key="index" :label="item.id" border>{{
              item.name }}</el-radio-button>
          </el-radio-group>
        </div>
      </el-card>

    </div>

    <div class="page-main flex space-between" ref="pageMain">

      <el-card shadow="hover" style="width:42.5%;height:100%;" v-loading="state.tableData.loading">

        <el-table :data="state.tableData.data" border style="width: 100%" :height="state.tableHeight"
          @row-click="handleRowClick" :row-style="rowStyle">
          <el-table-column label="日间序号" show-overflow-tooltip align="center">
            <template #default="scope">
              {{ scope.row.serialNumber ? scope.row.serialNumber : '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="patient.name" label="患者姓名" width="90" show-overflow-tooltip
            align="center"></el-table-column>
          <el-table-column label="手术科室" show-overflow-tooltip align="center">
            <template #default="scope">
              {{ (scope.row.operation && scope.row.operation.department) ?
                scope.row.operation.department.departmentName : '-' }}
            </template>
          </el-table-column>
          <el-table-column label="主刀医生" width="90" show-overflow-tooltip align="center">
            <template #default="scope">
              {{ (scope.row.operation && scope.row.operation.chiefDoctor) ? scope.row.operation.chiefDoctor.name : '-' }}
            </template>
          </el-table-column>
          <el-table-column label="联系方式" width="120" show-overflow-tooltip align="center">
            <template #default="scope">
              {{ scope.row.patient.phone ? scope.row.patient.phone : '-' }}
            </template>
          </el-table-column>
          <el-table-column label="当前状态" show-overflow-tooltip align="center">
            <template #default="scope">
              {{ scope.row.status && scope.row.status != 0 ? state.statusObj[scope.row.status] : '-' }}
            </template>
          </el-table-column>

        </el-table>


        <div class="pagination-box">
          <el-pagination @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange" class="mt15"
            :pager-count="5" :page-sizes="[10, 20, 30]" v-model:current-page="state.apiData.page" background
            v-model:page-size="state.apiData.pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="state.tableData.total">
          </el-pagination>
        </div>

      </el-card>

      <el-card shadow="hover" style="width:56.5%;height:100%;">
        <div class="bed-box" v-loading="state.bedLoading" element-loading-background="#fff">
          <div class="bed-list">
            <div class="bed-item flex " v-for="(item, index) in state.bedList" :key="index"
              :class="item.patientRecord ? 'selected' : ''">

              <!-- 如果为可选 -->
              <div v-if="!item.patientRecord" class="item-content" :class="item.isDisable == 1?'disabled':''" @click="changeSelectBed(item)">
                <div class="nfo-box no-user-box flex justify-center align-center">
                  <div class="no-user-center flex ">
                    <div class="bed-number">
                      {{ item.number + '床' }}
                    </div>
                    <img v-if="item.isDisable == 1" :src="lock" alt="" class="re-lock">
                    <div v-else class="re-btm">床位预约</div>
                  </div>
                </div>
              </div>

              <!-- 不可选 -->
              <div v-else class="item-content " >

                <!-- 若当前登录人为管理员或该患者主刀医生 才可看见详细信息 否则只显示占位 -->
                <div v-if="currentUserId == item.patientRecord.operation.chiefDoctorId || isAdmin" class="info-box" @click="openDrawer(item.patientRecord.id)">
                  <div class="bed-number">
                    {{ item.number + '床' }}
                  </div>
                  <div class="patient-infos">

                    <span class="top-line flex space-between align-center">
                      <span>{{ item.patientRecord.patient.name }}</span>
                      <span>{{ sexObj[item.patientRecord.patient.gender] }}</span>
                      <span>{{ item.patientRecord.age ? item.patientRecord.age : '-' }}</span>
                    </span>

                    <div class="flex space-between align-start" style="margin:1.5% 0;">
                      <el-tooltip class="box-item" effect="dark" :content="item.patientRecord.preDiagnosis"
                        :placement="top">
                        <span class="pre ellipsis">{{ item.patientRecord.preDiagnosis }}</span>
                      </el-tooltip>
                      <span class="flex align-center">
                        <span class="anesthesia"> {{
                          item.patientRecord.anesthesiaAssessment &&
                          item.patientRecord.anesthesiaAssessment.anesthesiaMode ?
                          item.patientRecord.anesthesiaAssessment.anesthesiaMode.name : '-'
                        }}</span>
                        |
                        <span class="doctor-name ellipsis"> {{
                          item.patientRecord.operation && item.patientRecord.operation.chiefDoctor ?
                          item.patientRecord.operation.chiefDoctor.name : '-'
                        }}</span>
                      </span>

                    </div>
                    <div class="flex space-between">
                      <el-tooltip class="box-item" effect="dark" :content="item.patientRecord.operation && item.patientRecord.operation.operation ?
                            item.patientRecord.operation.operation.name : '-'" :placement="top">
                        <div class="operation-name ellipsis">
                          {{
                            item.patientRecord.operation && item.patientRecord.operation.operation ?
                            item.patientRecord.operation.operation.name : '-'
                          }}
                        </div>
                      </el-tooltip>
                      <div class="cancel-apply" v-if="isShowCancelBtn(item.patientRecord.id)"
                        @click.stop="cancelApplyBed(item.patientRecord.id)">
                        取消预约
                      </div>
                    </div>

                  </div>
                </div>
                <div v-else class="info-box disabled">
                  <div class="bed-number">
                    {{ item.number + '床' }}
                  </div>
                  <img class="bed-img" :src="icon" alt="">
                </div>
              </div>
            </div>
          </div>

        </div>
      </el-card>
    </div>

    <patientDetailDrawer ref="patientDetailDrawerRef" @refresh="drawerCloseRefresh()"  />
  </div>
</template>

<script setup name="dsProcess-bedOverview">
import { useRouter } from 'vue-router';
import { getCurrentInstance } from 'vue';
import { dsApi } from '/@/api/ds/index';
import { toolsApi } from '/@/api/tools/index';
import { transListToObj } from '/@/utils/arrayOperation'
import { ElMessage } from 'element-plus';
import { usePageDatas } from '/@/stores/pageDatas';
import { usePatientDetail } from '/@/stores/patientDetail';
import { useUserInfo } from '/@/stores/userInfo'
import { storeToRefs } from 'pinia'
import {
  ArrowLeftBold,
  ArrowRightBold,
  Postcard
} from '@element-plus/icons-vue'
import { formatWeedDay } from '/@/utils/formatTime';
import dayjs from 'dayjs'
import icon from '/@/assets/bed-lock.png';
import { throttle } from '/@/utils/toolsValidate';
import lock from '/@/assets/lock.png';
const patientDetailDrawer = defineAsyncComponent(() => import('./components/patientDetailDrawer.vue'));

const Patientstores = usePatientDetail();
const UserInfoStores = useUserInfo()
const { sexObj } = storeToRefs(Patientstores);
const { userInfos } = storeToRefs(UserInfoStores);
const stores = usePageDatas();
const { patientListApiData } = storeToRefs(stores);
// 引入组件
const Breadcrumb = defineAsyncComponent(() => import('/@/layout/navBars/breadcrumb/breadcrumb.vue'));

const router = useRouter();

const patientDetailDrawerRef = ref()

// 定义变量内容
const state = reactive({
  apiData: {
    page: 1,
    pageSize: 10,
    departmentId: '',
    search: '',
    status: 0,
    type: 2
  },
  tableData: {
    data: [],
    loading: false,
    total: 0
  },
  tableHeight: '30vh',
  departmentList: [],
  statusObj: null,
  patientRecordId: null,
  patientChiefDoctorId: null,
  dayArr: [],
  checkedDay: '',
  hospitalAreaId: '1',
  bedStatus: '',
  bedLoading: false,
  bedList: [],
  hospitalAreaList: [],
  patientOperationAt: null,
});

// 页面加载时
onMounted(() => {
  getList()
  getTools()
  getDays()
  state.tableHeight = getCurrentInstance().refs.pageMain.offsetHeight - 130 + "px";
});

const currentUserId = computed(() => {
	return userInfos.value.id;
});

// 是否为管理员
const isAdmin = computed(() => {
  const hasAdmin = userInfos.value.role.find(item=>{
    return item.slug == 'administrator'
  })

  if(hasAdmin && hasAdmin != undefined){
    return true
  }else{
	  return false;
  }
});

const searchChange = () => {
  state.apiData.page = 1
  getList()
}



const handleRowClick = (row) => {
  state.patientRecordId = row.id
  state.patientChiefDoctorId = row.operation ? row.operation.chiefDoctorId : null
  if (row.operation && row.operation.operationAt) {
    state.patientOperationAt = row.operation.operationAt
  } else {
    state.patientOperationAt = null
  }
  getDays()
}


// 分页改变
const onHandleSizeChange = (val) => {
  state.apiData.pageSize = val;
  getList();
};

const onHandleCurrentChange = (val) => {
  state.apiData.page = val;
  getList();
};


// 如果当前行index 是点击行，就改变颜色
const rowStyle = ({ row, rowIndex }) => {
  if (row.id == state.patientRecordId) {
    return {
      'background-color': 'rgba(48, 129, 244, 0.08) !important'
    }
  }
}


// 获取列表
const getList = () => {
  state.tableData.loading = true
  state.patientChiefDoctorId = null
  dsApi().patientRecords(state.apiData).then(res => {
    state.tableData.loading = false
    state.tableData.data = res.data.items
    state.tableData.total = res.data.total
  }).catch(() => {
    state.tableData.loading = false
  })

}


const recordAtChange = (e) => {
  if (e) {
    state.apiData.recordAt = e
  } else {
    state.apiData.recordAt = []
  }
  getList();
}

const operationAtChange = (e) => {
  if (e) {
    state.apiData.operationAt = e
  } else {
    state.apiData.operationAt = []
  }
  getList();
}

// 是否显示取消预约
const isShowCancelBtn = (id) => {
  // 如果没选择患者 则都展示取消
  if(!state.patientRecordId){
    return true
  }else{ // 否则只展示选中患者的取消
    if(state.patientRecordId === id){
      return true
    }else{
      return false
    }
  }
}




const getTools = () => {
  getDepartmentList()
  getPatientStatus()
  getHospitalArea()
}

const getDepartmentList = () => {
  toolsApi().departmentList({ all: 1 }).then(res => {
    state.departmentList = res.data
  })
}

const getPatientStatus = () => {
  toolsApi().patientStatus().then(res => {
    state.statusObj = transListToObj(res.data, 'value', 'text')
  })
}

const getDays = () => {
  const dayArr = []
  if (state.patientOperationAt) {
    dayArr.push(dayjs(state.patientOperationAt).startOf('day').unix())
    dayArr.push(dayjs(state.patientOperationAt).startOf('day').add(1, "days").unix())
    dayArr.push(dayjs(state.patientOperationAt).startOf('day').add(2, "days").unix())
    dayArr.push(dayjs(state.patientOperationAt).startOf('day').add(3, "days").unix())
    dayArr.push(dayjs(state.patientOperationAt).startOf('day').add(4, "days").unix())
    dayArr.push(dayjs(state.patientOperationAt).startOf('day').add(5, "days").unix())
    dayArr.push(dayjs(state.patientOperationAt).startOf('day').add(6, "days").unix())

    state.checkedDay = dayjs(state.patientOperationAt).startOf('day').unix()
  } else {
    dayArr.push(dayjs().startOf('day').unix())
    dayArr.push(dayjs().startOf('day').add(1, "days").unix())
    dayArr.push(dayjs().startOf('day').add(2, "days").unix())
    dayArr.push(dayjs().startOf('day').add(3, "days").unix())
    dayArr.push(dayjs().startOf('day').add(4, "days").unix())
    dayArr.push(dayjs().startOf('day').add(5, "days").unix())
    dayArr.push(dayjs().startOf('day').add(6, "days").unix())

    state.checkedDay = dayjs().startOf('day').unix()
  }

  state.dayArr = dayArr
  getBedList()
}

const formatValue = (value) => {
  return formatWeedDay(dayjs(value * 1000).day()) + ' ' + dayjs(value * 1000).format("MM.DD")
}

const changeDay = (value) => {
  state.checkedDay = value
  // state.patientRecordId = null
  getBedList()
}

const nextOrPrevDayArr = (type) => {
  if (type == 'next') {
    const nextDayArr = []
    nextDayArr.push(state.dayArr[5] + 86400)
    nextDayArr.push(state.dayArr[5] + 86400 * 2)
    nextDayArr.push(state.dayArr[5] + 86400 * 3)
    nextDayArr.push(state.dayArr[5] + 86400 * 4)
    nextDayArr.push(state.dayArr[5] + 86400 * 5)
    nextDayArr.push(state.dayArr[5] + 86400 * 6)
    nextDayArr.push(state.dayArr[5] + 86400 * 7)
    state.dayArr = nextDayArr
    state.checkedDay = nextDayArr[0]
  } else {
    const prevDayArr = []
    prevDayArr.push(state.dayArr[0] - 86400 * 7)
    prevDayArr.push(state.dayArr[0] - 86400 * 6)
    prevDayArr.push(state.dayArr[0] - 86400 * 5)
    prevDayArr.push(state.dayArr[0] - 86400 * 4)
    prevDayArr.push(state.dayArr[0] - 86400 * 3)
    prevDayArr.push(state.dayArr[0] - 86400 * 2)
    prevDayArr.push(state.dayArr[0] - 86400)

    state.dayArr = prevDayArr
    state.checkedDay = prevDayArr[0]
  }
  getBedList()
}

const getBedList = () => {
  state.bedLoading = true
  const apiData = {
    hospitalAreaId: state.hospitalAreaId,
    status: state.bedStatus,
    operationAt: dayjs(state.checkedDay * 1000).format('YYYY-MM-DD'),
  }
  toolsApi().hospitalBeds(apiData).then(res => {
    state.bedLoading = false
    state.bedList = res.data
  }).catch(() => {
    state.bedLoading = false
  })
}

const getHospitalArea = () => {
  toolsApi().hospitalArea().then(res => {
    state.hospitalAreaList = res.data
  }).catch(() => {
  })
}

const searchBedChange = () => {
  getBedList()
}



const changeSelectBed = throttle((item) => {
  if (!state.patientRecordId) {
    ElMessage.warning('请先选择患者');
    return;
  } 

  if(!isAdmin.value && currentUserId.value != state.patientChiefDoctorId ){
    ElMessage.warning('无操作权限');
    return
  }

  if (item.isDisable == 1) {
    ElMessage.warning('该床位已被管理员禁用');
    return
  }
  
  const apiData = {
    patientRecordId: state.patientRecordId,
    hospitalAreaId: state.hospitalAreaId,
    hospitalBedId: item.id,
    operationAt: dayjs(state.checkedDay * 1000).format('YYYY-MM-DD'),
  }

  dsApi().recordBed(apiData).then(res => {
    ElMessage.success('操作成功');
    // state.patientOperationAt = dayjs(state.checkedDay * 1000).format('YYYY-MM-DD')
    state.patientOperationAt = null
    getDays()
    getList()
  }).catch(() => {
    ElMessage.error(res.errMsg);
  })
} ,500)


const cancelApplyBed = (id) => {
  const apiData = {
    prid: id,
  }

  dsApi().cancelBed(apiData).then(res => {
    ElMessage.success('操作成功');
    state.patientOperationAt = null
    getDays()
    getList()
  }).catch(() => {

  })
}

const openDrawer = (id) => {
  patientDetailDrawerRef.value.openDrawer(id);
}

const drawerCloseRefresh = () => {
  getBedList()
}

</script>

<style lang="scss" scoped>

.header-search {
  background-color: #f5f5f5;

  .search-l,
  .search-r {
    height: 114px;
  }

  .search-l {
    width: 42.5%;
  }

  .search-r {
    width: 56.5%;
  }

  .search-txt {
    color: #666;
    margin-right: 10px;
    font-size: 13px;
  }
}

.page-main {
  height: calc(100vh - 50px - 190px);
  padding-top: 0;
}

.time-line {
  flex-wrap: wrap;
  padding: 0px 0;
  margin: -10px 0 10px;

  .time-top,
  .time-bottom {
    width: 100%;
  }

  .time-list {
    width: calc(100% - 120px);
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    gap: 15px;
    overflow-x: auto;
    overflow-y: hidden;
  }

  .time-item {
    position: relative;
    height: 44px;
    text-align: center;
    line-height: 44px;
    background-color: #F9F9F9;
    color: #333;
    border-radius: 8px;
    border: 1px solid #C9C9C9;
    padding: 0 10px;
    cursor: pointer;
    font-weight: 500;
    font-size: 13px;

    &.active {
      color: #409EFF;
      background-color: #fff;
      border: 1px solid #409EFF;
    }

  }




}

.bed-box {
  width: 100%;
  height: calc(100vh - 350px);
}

.bed-list {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  // grid-template-rows: repeat(7, 1fr);
  gap: 0px;
  width: 100%;
  height: 100%;
  border: 0.5px solid #CECECE;

  .bed-item {
    flex-direction: column;
    // height: 74px;
    border: 0.5px solid #CECECE;
    background: #F9F9F9;
    padding: 6px;

    &.selected {
      background-color: rgba(166, 202, 240, 0.2);

    }

    .item-content {
      position: relative;
      display: flex;
      flex-direction: column;
      height: 100%;
      cursor: pointer;

      &.disabled {
        cursor: no-drop;
      }

      .no-user-box {
        position: relative;
        width: 100%;
        height: 100%;

        .no-user-center {
          position: absolute;
          left: 50%;
          transform: translateX(-50%);
          top: 0;
          flex-direction: column;

          .bed-number {
            color: #000;
            font-weight: 500;
            text-align: center;
          }

          .re-btm {
            width: 88px;
            height: 28px;
            background: #FFFFFF;
            border-radius: 2px;
            border: 1px dashed #D9D9D9;
            text-align: center;
            line-height: 26px;
            margin-top: 2%;
            color: #666;
          }
        }
      }

      .info-box {
        display: flex;
        justify-content: center;
        align-items: center;
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        &.disabled{
          cursor: no-drop;
        }

        .bed-img{
          width: 35px;
          height: 35px;
        }

        .bed-number {
          position: absolute;
          right: -8px;
          top: -8px;
          width: 51px;
          height: 18px;
          background: #0077D7;
          box-shadow: 0px 2px 4px 0px rgba(26, 79, 0, 0.13);
          border-radius: 11px 0px 11px 11px;
          color: #fff;
          font-size: 12px;
          text-align: center;
        }

        .patient-infos {
          width: 100%;
          height: 100%;
          font-size: 12px;

          .cancel-apply {
            padding: 2px 10px;
            background-color: #F56C6C;
            color: #fff;
            border-radius: 11px;
            white-space: nowrap;
            transform: scale(0.9);
          }

          .pre {
            width: 49%;
          }

          .anesthesia {
            display: inline-block;
            max-width: 40px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          .top-line {
            width: 60%;
          }


        }
      }
    }



  }
}
</style>
